package handler

import (
	"context"
	"google.golang.org/grpc/codes"
	"google.golang.org/grpc/status"
	"google.golang.org/protobuf/types/known/emptypb"
	"mxshop_srvs/goods_srv/global"
	"mxshop_srvs/goods_srv/model"
	"mxshop_srvs/goods_srv/proto"
)

// 轮播图
func (g *GoodsServer) BannerList(ctx context.Context, rep *emptypb.Empty) (*proto.BannerListResponse, error) {

	var bannerListResponse proto.BannerListResponse
	var bannerList []model.Banner
	result := global.DB.Find(&bannerList)
	if result.Error != nil {
		return nil, status.Error(codes.Internal, result.Error.Error())
	}
	bannerListResponse.Total = int32(result.RowsAffected)
	for _, banner := range bannerList {
		bannerResponse := proto.BannerResponse{
			Id:    banner.ID,
			Index: banner.Index,
			Image: banner.Image,
			Url:   banner.Url,
		}
		bannerListResponse.Data = append(bannerListResponse.Data, &bannerResponse)
	}
	return &bannerListResponse, nil
}

func (g *GoodsServer) CreateBanner(ctx context.Context, req *proto.BannerRequest) (*proto.BannerResponse, error) {

	banner := model.Banner{
		Image: req.Image,
		Url:   req.Url,
		Index: req.Index,
	}
	if result := global.DB.Save(banner); result.Error != nil {
		return nil, status.Error(codes.Internal, result.Error.Error())
	}
	return &proto.BannerResponse{Id: banner.ID}, nil

}

func (g *GoodsServer) DeleteBanner(ctx context.Context, req *proto.BannerRequest) (*emptypb.Empty, error) {

	if result := global.DB.Delete(model.Banner{}, req.Id); result.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "轮播图不存在")
	}
	return &emptypb.Empty{}, nil

}

func (g *GoodsServer) UpdateBanner(ctx context.Context, req *proto.BannerRequest) (*emptypb.Empty, error) {

	var banner model.Banner
	if result := global.DB.Find(&banner, req.Id); result.RowsAffected == 0 {
		return nil, status.Error(codes.NotFound, "轮播图不存在")
	}
	banner.Url = req.Url
	banner.Image = req.Image
	banner.Index = req.Index
	if result := global.DB.Save(&banner); result.Error != nil {
		return nil, status.Error(codes.Internal, result.Error.Error())
	}
	return &emptypb.Empty{}, nil

}
